<?php
namespace app\gateway\controller;

use app\common\traits\Provide;
use \GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;

class Events
{
    use Provide;
    public static function onMessage($client_id, $message)
    {
        $message_data = json_decode($message, true);
        if (!isset($message_data['token'])) {
            return;
        }
        $user_info = self::getUserInfoByToken($message_data['token']);
        if(!$user_info)
        {
            return;
        }
        $room_info = self::getRoomInfo($user_info['room_id']);
        if(!$room_info || $room_info['room_state'] !=1)
        {
            return;
        }
        //普通房间
        $general_channel = $room_info['room_id'].'_general';
        //权利房间
        $power_channel   = $room_info['room_id'].'_power';
        //权利分组
        $power_role      = explode(',', $room_info['power_role']);
        //房间消息
        $room_msg        = 'room_msg_'.$room_info['room_id'];
        //在线客服分组
        $service_group   = 'service_group_'.$room_info['room_id'];

        switch ($message_data['type'])
        {
            case 'ping':
                $msg['msg_type'] = 'ping';
                $msg['time']     = time();
                Gateway::sendToCurrentClient(json_encode($msg));
                return;

            case 'new_client':
                if(Gateway::isUidOnline($user_info['user_id']))
                {
                    return;
                }
                $_SESSION['room_id']     = $user_info['room_id'];
                $_SESSION['user_name']   = $user_info['user_name'];
                $_SESSION['user_id']     = $user_info['user_id'];
                $_SESSION['avatar']      = $user_info['avatar'];
                $_SESSION['user_role']   = $user_info['user_role'];
                $_SESSION['token']       = $message_data['token'];
                $_SESSION['client_id']   = $client_id;

                //user_id绑定client_id
                Gateway::bindUid($client_id, $user_info['user_id']);
                //加入相应分组
                if(in_array($user_info['user_role'], $power_role))
                {
                    Gateway::joinGroup($client_id, $power_channel);
                }else{
                    Gateway::joinGroup($client_id, $general_channel);
                }
                //权利分组人员列表
                $power_list = Gateway::getClientSessionsByGroup($power_channel);
                //普通分组人员列表
                $general_list = array_slice(Gateway::getClientSessionsByGroup($general_channel), 0, 50);
                //合并分组
                $all_list = self::array_unset(array_merge($power_list, $general_list), 'token');
                //获取普通分组的在线人数
                $msg['client_nums'] = Gateway::getUidCountByGroup($general_channel);
                //取出在线的客服列表数
                $service_list = Gateway::getClientSessionsByGroup($service_group);

                $msg['msg_id']    = self::getRandomId();
                $msg['msg_type']  = 'new_client';
                $msg['client_id'] = $client_id;
                $msg['token']     = $message_data['token'];
                $msg['user_id']   = $user_info['user_id'];
                $msg['user_name'] = $user_info['user_name'];
                $msg['avatar']    = $user_info['avatar'];
                $msg['user_role'] = $user_info['user_role'];
                $msg['service_list'] = $service_list;
                $msg['time']      = date('Y-m-d H:i:s');

                if(in_array($user_info['user_role'], $power_role))
                {
                    $msg['client_flag'] = 'all_client';
                    $msg['client_list'] = $all_list;
                    Gateway::sendToGroup($power_channel, json_encode($msg));
                }else{
                    //给分组里的客户推送有新的客户端加入（排除当前客户端）
                    $msg['client_flag'] = 'new_client';
                    Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg) ,[$client_id]);
                    //给当前客户端发送全部用户列表
                    $msg['client_flag'] = 'all_client';
                    $msg['client_list'] = $general_list;
                    Gateway::sendToCurrentClient(json_encode($msg));
                }
                return;

            case 'message':
                $msg['msg_id']      = self::getRandomId();
                $msg['msg_type']    = 'message';
                $msg['from_client'] = $client_id;
                $msg['from_user_id']= $user_info['user_id'];
                $msg['user_role']   = $user_info['user_role'];
                $msg['from_name']   = $user_info['user_name'];
                $msg['from_avatar'] = $user_info['avatar'];
                $msg['speak_state'] = $user_info['speak_state'];  //发言状态 1正常 0禁言
                $msg['from_token']  = $message_data['token'];
                $msg['to_client']   = $message_data['to_client'];
                $msg['to_name']     = $message_data['to_name'];
                $msg['content']     = $message_data['content'];
                $msg['is_examine']  = 1;  //是否审核消息 0未审核 1审核过
                $msg['msg_state']   = 1;  //消息状态1正常  0撤回状态
                $msg['date']        = date('Y-m-d H:i:s');
                $msg['time']        = time();

                //判断用户是否是禁言状态
                if($user_info['speak_state'] == 0)
                {
                    return;
                }
                //判断发言用户是否是权利组用户如果不是先转发到权利组用户
                if(in_array($user_info['user_role'], $power_role))
                {
                    //存储消息返回消息的redis索引值
                    $msg['from_name'] = $user_info['user_name'];
                    $msg['msg_cache_index'] = self::redis()->rPush($room_msg, json_encode($msg));
                    //如果不是对所有人发送
                    if($message_data['to_client'] != 'all')
                    {
                        $msg['from_name']   = $user_info['user_name'].'对你说';
                        Gateway::sendToUid($message_data['to_client'], json_encode($msg));
                        $msg['from_name']   = $user_info['user_name'].'对'.$msg['to_name'].'说';
                        Gateway::sendToGroup($power_channel, json_encode($msg));
                    }else{
                        $msg['from_name']   = $user_info['user_name'];
                        Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
                    }
                }else{
                    if($room_info['message_state'] == 1)
                    {
                        $msg['is_examine'] = 0; //更改消息状态为未审核
                        //存储消息返回消息的redis索引值
                        $msg['from_name'] = $user_info['user_name'];
                        $msg['msg_cache_index'] = self::redis()->rPush($room_msg, json_encode($msg));

                        Gateway::sendToGroup($power_channel, json_encode($msg));
                        $msg['from_name'] = '你说';
                        Gateway::sendToCurrentClient(json_encode($msg));
                    }else{
                        //存储消息返回消息的redis索引值
                        $msg['msg_cache_index'] = self::redis()->rPush($room_msg, json_encode($msg));
                        Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
                    }
                }
                //把消息索引再存入到Redis中
                $msg_info = self::redis()->lindex($room_msg, $msg['msg_cache_index']-1);
                $msg_info = json_decode($msg_info, true);
                $msg_info['msg_cache_index'] = $msg['msg_cache_index'];
                self::redis()->lSet($room_msg, $msg['msg_cache_index']-1, json_encode($msg_info));
                return;

            //开启定时器自动发送消息
            case 'start_auto_speak':
                if(!in_array($user_info['user_role'], $power_role))
                {
                    return;
                }
                $auto_speak = self::redis()->lLen('auto_speak_list');
                if($auto_speak)
                {
                    $speak_role  = (int)$message_data['speak_role'];
                    $msg_content = self::redis()->lIndex('auto_speak_list', mt_rand(0, $auto_speak-1));
                    if($speak_role == 1)
                    {
                        $msg['from_name']   = self::getTouristName(6);
                    }else{
                        $msg['from_name']   = getRandName();
                    }

                    $msg['msg_id']      = self::getRandomId();
                    $msg['msg_type']    = 'message';
                    $msg['from_client'] = $client_id;
                    $msg['from_user_id']= mt_rand();
                    $msg['user_role']   = $speak_role;
                    $msg['from_avatar'] = self::getAvatar($speak_role);
                    $msg['speak_state'] = 1;
                    $msg['from_token']  = $msg['msg_id'];
                    $msg['to_client']   = 'all';
                    $msg['to_name']     = '大家';
                    $msg['content']     = $msg_content;
                    $msg['is_examine']  = 1;  //是否审核消息 0未审核 1审核过
                    $msg['msg_state']   = 1;  //消息状态1正常  0撤回状态
                    $msg['date']        = date('Y-m-d H:i:s');
                    $msg['time']        = time();
                    Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
                }
                return;

            //关闭定时器自动发送消息
            case 'stop_auto_speak':
                //清掉定时任务
                if(isset($_SESSION['auto_speak_timer_id']))
                {
                    Timer::del($_SESSION['auto_speak_timer_id']);
                }
                return;

            //客服上线
            case 'service_login':
                $_SESSION['service_id']  = $user_info['service_id'];
                $_SESSION['service_name']  = $user_info['service_name'];
                $_SESSION['service_avatar']  = $user_info['service_avatar'];
                $_SESSION['token']       = $message_data['token'];
                $_SESSION['client_id']   = $client_id;

                Gateway::joinGroup($client_id, $service_group); //加入客服分组
                //user_id绑定client_id
                Gateway::bindUid($client_id, $user_info['user_id']);
                //分发给当前在线成员有客服上线了
                $service_list = Gateway::getClientSessionsByGroup($service_group);
                $service_list[$client_id] = $_SESSION;
                $msg = array(
                    'msg_type'=>'service_login',
                    'service_list' =>$service_list
                );
                Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));

                return;

            //用户打开客服窗口时
            case 'open_service':
                //user_id绑定client_id
                Gateway::bindUid($client_id, $user_info['user_id']);
                return;

            //客服消息推送
            case 'service_message':
                $msg['receive_id'] = $message_data['receive_id']; //接收消息人ID
                //重新封装layim消息返回格式
                $msg['username'] = $message_data['from_name']; //发送人用户名
                $msg['avatar']   = $message_data['from_head']; //发送人头像
                $msg['id']       = $user_info['user_id']; //发送人id
                $msg['type']     = 'friend'; //聊天窗口来源类型
                $msg['content']  = $message_data['message_content']; //消息内容
                $msg['cid']      = self::getRandomId(); //消息id
                $msg['mine']     = false; //是否我发送的消息，如果为true，则会显示在右方
                $msg['fromid']   = $user_info['user_id']; //发送人id
                $msg['timestamp'] = time()*1000; //发送时间毫秒数
                $json_new_message = json_encode($msg);
                Gateway::sendToUid($msg['receive_id'], $json_new_message);
                return;

            default:
                return;
        }
    }

    /*
     * 客户端离线
     */
    public static function onClose($client_id)
    {
        $token = $_SESSION['token'];
        $user_info = self::getUserInfoByToken($token);
        //普通房间
        $general_channel = $user_info['room_id'].'_general';
        //权利房间
        $power_channel   = $user_info['room_id'].'_power';

        $msg['msg_type'] = 'close_client';
        $msg['client_id'] = $client_id;
        $msg['client_nums'] = Gateway::getClientIdCountByGroup($general_channel);
        Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
    }
}
